package error

import (
	"errors"
	"fmt"
	"strconv"
	"time"
)

func foo(input string) (string, error) {
	if input == "normal" {
		return input, nil
	} else {
		return input, errors.New("empty name")
	}
}

func errorT() {
	a, e := foo("dasd")
	if e != nil {
		fmt.Println("error", e)
	} else {
		fmt.Println("ok", a)
	}
}

type MyError struct {
	When time.Time
	What string
}

func (e *MyError) Error() string {
	return fmt.Sprintf("at %v, %s",
		e.When, e.What)
}

func run() error {
	return &MyError{
		time.Now(),
		"it didn't work",
	}
}

func invalidSyntax() {
	if err := run(); err != nil {
		fmt.Println(err)
	}

	i, err := strconv.Atoi("a42")
	if err != nil {
		fmt.Printf("couldn't convert number: %v\n", err)
		return
	}
	fmt.Println("Converted integer:", i)
}

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
	// todo Sqrt 接受到一个负数时，应当返回一个非 nil 的错误值。复数同样也不被支持
	return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))
}

func Sqrt(x float64) (float64, error) {
	if x < 0 {
		return 0, ErrNegativeSqrt(x)
	}
	return 0, nil
}

func errorPrint() {
	fmt.Println(Sqrt(2))
	fmt.Println(Sqrt(-2))
}
